 <template>
  <div>
    <el-row>
      <!--检索-->
      <el-form :inline="true" :model="search" class="demo-form-inline">
        <el-input v-if="false" v-model="search.pageNum"></el-input>
        <el-input v-if="false" v-model="search.pageSize"></el-input>
        <el-col :span="4">
          <el-input
            v-model="search.roleName"
            placeholder="请输入名称"
          ></el-input>
        </el-col>
        <el-col :span="4"
          ><div>
            <el-input
              v-model="search.createBy"
              placeholder="请输入创建人"
            ></el-input></div
        ></el-col>
        <el-col :span="12"
          ><div>
            <el-button type="primary" icon="el-icon-search" @click="searchBtn"
              >搜索</el-button
            >
            <el-button type="info" icon="el-icon-loading" @click="emptyBtn"
              >刷新</el-button
            >
          </div>
        </el-col></el-form
      >
      <el-button
        type="primary"
        @click="addBtn"
        icon="el-icon-circle-plus"
        >新增</el-button
      >
      <!--功能列表-->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="roleId" label="角色ID" sortable> </el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="createBy" label="创建人">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
        </el-table-column>
        <el-table-column prop="updateBy" label="更新人">
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间">
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          :formatter="getStatusName"
        ></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="small"
              @click="updateRole(scope.$index, scope.row)"
              icon="el-icon-edit"
              type="success"
              >编辑</el-button
            >
            <el-button
              size="small"
              @click="deleteRole(scope.$index, scope.row)"
              icon="el-icon-delete"
              type="danger"
              >删除</el-button
            >
            <el-button
              size="small"
              @click="showRoleDialog(scope.row.roleId)"
              icon="el-icon-star-off"
              type="primary"
              >分配功能</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!--分页功能-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNum"
        :page-sizes="[1, 2, 3, 5, 10, 20]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
      >
      </el-pagination>
      <!--新增/修改 Form -->
      <el-dialog title="角色管理" :visible.sync="editRoleState">
        <el-form :model="form">
          <el-form-item label="角色名称" :label-width="formLabelWidth">
            <el-input
              v-model="form.roleName"
              placeholder="角色名称"
              auto-complete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态" :label-width="formLabelWidth">
            <el-radio v-model="form.status" label="0">启动</el-radio>
            <el-radio v-model="form.status" label="1">禁用</el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editRoleState = false">取 消</el-button>
          <el-button type="primary" @click="saveRole">确 定</el-button>
        </div>
      </el-dialog>
      <!--分配功能 Form -->
<!--      <el-dialog title="分配功能" :visible.sync="editRolePower">-->
<!--        <el-tree-->
<!--          :data="powerData"-->
<!--          show-checkbox-->
<!--          :default-checked-keys="[5]"-->
<!--          node-key="id"-->
<!--          ref="tree"-->
<!--          highlight-current-->
<!--          :props="defaultProps"-->
<!--        >-->
<!--        </el-tree>-->
<!--        <div slot="footer" class="dialog-footer">-->
<!--          <el-button @click="editRolePower = false">取 消</el-button>-->
<!--          <el-button type="primary" @click="saveRolePower">确 定</el-button>-->
<!--        </div>-->
<!--      </el-dialog>-->
<!--      &lt;!&ndash;角色授权弹出框&ndash;&gt;-->
<!--      <el-dialog title="权限菜单" :visible.sync="menuTreeVisible">-->
<!--        <el-tree-->
<!--          :data="treeData"-->
<!--          :props="defaultProps"-->
<!--          node-key="id"-->
<!--          show-checkbox-->
<!--          ref="menuTree"-->
<!--          :default-checked-keys="nodeChecked"-->
<!--        ></el-tree>-->
<!--        <div slot="footer" class="dialog-footer">-->
<!--          <el-button @click="menuTreeVisible = false">取 消</el-button>-->
<!--          <el-button type="primary" @click="addRoleAndMenus()">确 定</el-button>-->
<!--        </div>-->
<!--      </el-dialog>-->
<!--      <el-dialog-->
<!--              title="分配权限"-->
<!--              :visible.sync="dialogVisible01"-->
<!--              width="30%"-->
<!--      >-->
<!--        <el-tree-->
<!--                :data="data"-->
<!--                show-checkbox-->
<!--                node-key="menuId"-->
<!--                ref="rootTree"-->
<!--                :props="defaultProps">-->
<!--        </el-tree>-->
<!--        <span slot="footer" class="dialog-footer">-->
<!--            <el-button @click="dialogVisible01 = false">取 消</el-button>-->
<!--            <el-button type="primary" @click="qr()">确 定</el-button>-->
<!--          </span>-->
<!--      </el-dialog>-->
      <el-dialog
              title="分配权限"
              :visible.sync="dialogVisible01"
              width="30%">
        <el-tree
                :data="data"
                show-checkbox
                class="permission-tree"
                node-key="id"
                ref="rootTree"
                :props="defaultProps">
        </el-tree>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible01 = false">取 消</el-button>
            <el-button type="primary" @click="qr">确 定</el-button>
          </span>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";
Vue.use(VueAxios, axios);

export default {
  data() {
    return {
      tableData: [],
      powerData: [],
      treeData: [],
      defaultProps: {
        children: "children",
        label: "menuName",
      },
      page: {},
      form: { status: "0" },
      powerform: {},
      search: { pageNum: 1, pageSize: 10 },
      formLabelWidth: "80px",
      editRoleState: false,
      editRolePower: false,
      menuTreeVisible: false,
      nodeChecked: [], //默认角色选中的权限菜单
      dialogVisible01:false,
      defaultChecked:[],
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      roleid:0
    };
  },
  created: function () {
    this.load();
    this.getMenu();
  },
  methods: {
    getMenu(){
      this.$http.get("/system/api/menu/allClass").then(resp=>{
        if (resp.data.code === 200){
          this.data=resp.data.data;
        }
      })
    },

    qr(){
      //获取被选中的权限ids
      let ids=[];
      let checkIds=this.$refs.rootTree.getCheckedKeys();
      let halfIds=this.$refs.rootTree.getHalfCheckedKeys();
      ids=checkIds.concat(halfIds);
      console.log(ids)
      axios.post("/system/api/menu/qr?roleId="+this.roleid+"&menuids="+ids).then(resp=> {
        this.$message.success("分配成功");
        this.dialogVisible01 = false;
      })
    },
    //分配权限
    showRoleDialog(roleId){
      this.$nextTick(() => {
        this.$refs.rootTree.setCheckedKeys([])
      })
      this.roleid=roleId;
      this.dialogVisible01=true;
      //1. 查询所有的权限
      //2. 当前角色具有的权限ID
      axios.get("/system/api/menu/showList?roleId="+roleId).then(resp=>{
        // this.data=resp.data.data.menus;
        this.defaultChecked=resp.data.data.menuids;
        //默认选中的树的数据
        setTimeout(() =>{
          resp.data.data.menuids.forEach(value => {
            this.$refs.rootTree.setChecked(value, true, false);
          })}, 100)
      })
    },
    //初始化数据
    load() {
      var _this = this;
      //页面初始化时，加载的方法
      this.$http
        .get("/system/api/role/queryAllByParam", {
          params: {
            pageNum: this.search.pageNum,
            pageSize: this.search.pageSize,
            roleName: this.search.roleName,
            roleId: this.search.roleId,
          },
        })
        .then((response) => {
          console.log(response.data);
          _this.tableData = response.data.data.records;
          _this.page = response.data.data;
          _this.total = response.data.data.total;
        });
    },
    //每页显示数量发生变化
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.search.pageSize = val;
      this.load();
    },
    //第几页发生变化
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.search.pageNum = val;
      this.load();
    },
    //查询
    searchBtn() {
      console.log(`当前页`);
      this.load();
    },
    emptyBtn() {
      this.search = {};
      this.search.pageNum = 1;
      this.search.pageSize = 5;
      this.load();
    },
    getStatusName(row, column, cellValue) {
      return cellValue == 0 ? "启动" : "禁用";
    },
    updateRole: function (index, row) {
      this.form = row;
      this.editRoleState = true;
    },
    deleteRole: function (index, row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var _this = this;
          axios
            .delete(
              "system/api/role/delete?roleId=" + row.roleId
            )
            .then(function (response) {
              console.log(response);
              if (response.status == 200) {
                if (response.data > 0) {
                  //提示成功
                  _this.$message({
                    type: "success",
                    message: "删除成功!",
                  });
                  //重新加载数据
                  _this.load();
                }
              }
            })
            .catch(function (error) {
              console.log(error);
              _this.$message.error("你错了。。。");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    setPower: function (index, row) {
      //给角色ID复制
      this.roleId = row.roleId;
      var _this = this;
      //初始化数据
      axios
        .get("http://localhost:9999/prs/menu/selectMenuTree")
        .then(function (response) {
          let tmpData = response.data.data;
          _this.treeData = tmpData;
          //查询并给勾选项赋值
          axios
            .get(
              "http://localhost:9999/prs/menu/selectAllMenuByRoleId?roleId=" +
                _this.roleId
            )
            .then(function (response) {
              _this.nodeChecked = response.data.data;
            });
        });
      //显示权限菜单对话框
      this.menuTreeVisible = true;
    },
    addRoleAndMenus() {
      //获取重新选中的节点
      let nodes = this.$refs.menuTree.getCheckedNodes();
      //判断至少选中一个节点
      if (nodes.length < 1) {
        this.$message.error("至少选中一个节点");
        return;
      }
      let tempMenuIds = "";
      //循环遍历
      for (var i = 0; i < nodes.length; i++) {
        tempMenuIds += nodes[i].id + ",";
      }
      tempMenuIds = tempMenuIds.substr(0, tempMenuIds.length - 1);
      console.log(
        "当前角色为：" +
          this.roleId +
          "，该角色对应新的权限ID为：" +
          tempMenuIds
      );
      var _this = this;
      //执行后台添加方法
      axios
        .post(
          "http://localhost:9999/prs/role/addRoleAndMenu?roleId=" +
            this.roleId +
            "&menuIds=" +
            tempMenuIds
        )
        .then(function (response) {
          console.log(response);
          if (response.status == 200) {
            if (response.data > 0) {
              //提示成功
              _this.$message({
                type: "success",
                message: "授权成功!",
              });
              //关闭弹框
              _this.menuTreeVisible = false;
              //重新加载数据
              _this.load();
            }
          }
        })
        .catch(function (error) {
          console.log(error);
          _this.$message.error("你错了。。。");
        });
    },
    saveRole() {
      console.log(this.form)
      var _this = this;
      if (
        this.form.roleId != null &&
        this.form.roleId != "" &&
        this.form.roleId != undefined
      ) {
        axios
          .put("/system/api/role/update", this.form)
          .then(function (response) {
            //正确请求时，回调函数
            console.log(response);
            _this.$message.success("修改成功")
            _this.load();
            _this.editRoleState = false;
          })
          .catch(function (error) {
            _this.editRoleState = false;
            _this.load();
            //失败处理
            console.log(error);
          });
      } else {
        axios
          .post("/system/api/role/insert", this.form)
          .then(function (response) {
            //正确请求时，回调函数
            console.log(response);
            _this.load();
            _this.editRoleState = false;
          })
          .catch(function (error) {
            //失败处理
            console.log(error);
          });
      }
    },
    addBtn() {
      this.form = {};
      this.editRoleState = true;
    },
    saveRolePower() {},
  },
};
</script>
<style>
</style>